package com.bdqn.tour.servlet.Tj;

import com.bdqn.tour.dao.TicketDao;
import com.bdqn.tour.pojo.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;


@WebServlet("/add-ticket")
public class AddTicketServlet extends HttpServlet {
    private static  final Logger logger = LoggerFactory.getLogger(AddTicketServlet.class.getName());
    private static final long serialVersionUID = 1L;
    private Connection connection;

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tourproject", "root", "123456");
        } catch (ClassNotFoundException | SQLException e) {
            throw new ServletException(e);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("add_ticket.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        String ticketType = request.getParameter("ticketType");
        String departureCity = request.getParameter("departureCity");
        String arrivalCity = request.getParameter("arrivalCity");
        String departureDateString = request.getParameter("departureDate");
        String startTimeString = request.getParameter("startTime");
        String endTimeString = request.getParameter("endTime");
        double price = Double.parseDouble(request.getParameter("price"));
        boolean hasInfantOption = "on".equals(request.getParameter("hasInfantOption"));
        boolean hasChildOption = "on".equals(request.getParameter("hasChildOption"));

        // 验证必填字段
        if (id == null || id.isEmpty() ||
                type == null || type.isEmpty() ||
                ticketType == null || ticketType.isEmpty() ||
                departureCity == null || departureCity.isEmpty() ||
                arrivalCity == null || arrivalCity.isEmpty() ||
                departureDateString == null || departureDateString.isEmpty() ||
                startTimeString == null || startTimeString.isEmpty() ||
                endTimeString == null || endTimeString.isEmpty()) {
            logger.error("Missing required fields in the form submission.");
            String encodedMessage = URLEncoder.encode("请填写所有必填字段", StandardCharsets.UTF_8);
            response.sendRedirect("error.jsp?message=" + encodedMessage);
            return;
        }


        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter timeFormatterHHmm = DateTimeFormatter.ofPattern("HH:mm");
        DateTimeFormatter timeFormatterHHmmss = DateTimeFormatter.ofPattern("HH:mm:ss");

        LocalDate departureDate = null;
        LocalTime startTime = null;
        LocalTime endTime = null;

        try {
            departureDate = LocalDate.parse(departureDateString, dateFormatter);

            // 尝试解析 HH:mm:ss 格式
            try {
                startTime = LocalTime.parse(startTimeString, timeFormatterHHmmss);
                endTime = LocalTime.parse(endTimeString, timeFormatterHHmmss);
            } catch (DateTimeParseException e) {
                // 如果解析失败，尝试解析 HH:mm 格式
                startTime = LocalTime.parse(startTimeString, timeFormatterHHmm);
                endTime = LocalTime.parse(endTimeString, timeFormatterHHmm);
            }
        } catch (DateTimeParseException e) {
            logger.error("Invalid date or time format", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid date or time format");
            return;
        }

        if (startTime == null || endTime == null) {
            logger.error("Start time and end time are required");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "End time is required");
            return;
        }

        Ticket ticket = new Ticket(id, type,ticketType, departureCity, arrivalCity, departureDate, startTime, endTime, price, hasInfantOption, hasChildOption);
        try {
            TicketDao ticketDAO = new TicketDao(connection);
            ticketDAO.addTicket(ticket);
            logger.info("Ticket added successfully: {}", ticket);
            response.sendRedirect("view-tickets");
        } catch (SQLException e) {
            logger.error("Failed to add ticket", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to add ticket");
            return;
        }
    }

    @Override
    public void destroy() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            logger.error("Failed to close connection", e);
        }
    }
}
